<template>
  <div class="container">
    <!-- 头部余额等 -->
    <div class="header">
      <BalanceChange v-if="change.show" :type="change.type" :amount="change.amount" />
      <img src="../../assets/img/world.png" alt />
      <div class="amount">
        <img src="../../assets/img/wsc.png" alt />
        <span>{{amount}}</span>
        <strong>{{$t("index.balance")}}</strong>
      </div>
      <div class="btns">
        <button @click="$router.push('/wallet')"></button>
        <button @click="$router.push('/announce')"></button>
      </div>
    </div>
    <!-- 游戏区域 -->
    <div class="gameArea">
      <div class="gameTitle">
        <!-- <p>众议院边缘1%</p> -->
        <div>
          <img src="../../assets/img/question_y.png" alt="" @click="$router.push('/analysis')">
          <span>{{$t("index.trend")}}</span>
          <SwitchButton :open="openTrend" @switchTrend="switchTrend" />
        </div>
      </div>
      <div class="trend">
        <Trend v-if="openTrend" ref="trend" />
        <div style="overflowY:auto;scrollLeft:10000" v-else ref="historyTrend">
          <dl v-for="(item,index) in arr" :key="index+'trend'">
            <dd :class="Number(item.times)<2?'redbg':'greenbg'"></dd>
            <dt>
              <span>{{item.issue}}</span>
              <br />
              <strong :style="{color:Number(item.times)<2?'#E74A61':'#36FFD6'}">{{item.times}}{{$t("index.times")}}</strong>
            </dt>
          </dl>
        </div>
      </div>
      <div class="graphCvas" ref="graphBox">
        <canvas ref="cvs_scale"></canvas>
        <canvas ref="canvas"></canvas>
        <Benefit v-if="benefitHint.show" :amount="benefitHint.amount" />
      </div>
      <Button :type="trendState" :amount="profit" @start="start" @next="next" @wating="wating" @fight="fight" />
      <div class="pour">
        <span>{{$t("index.amount")}}</span>
        <div>
          <div>
            <img src="../../assets/img/wsc.png" alt />
            <input type="number" v-model="pourAmount" @input="checkPourAmount">
          </div>
          <div>
            <button @click="changePour('/2')">/2</button>
            <button @click="changePour('2')">2{{$t("index.times")}}</button>
            <button @click="changePour('min')">{{$t("index.min")}}</button>
          </div>
        </div>
      </div>
      <div class="pour">
        <div>
          <p>{{$t("index.probab")}}<i :style="{color:autoFight?'':'#fff'}">{{autoFight?'0.99%':'- -'}}</i></p>
          <div class="switch">
            <span>{{$t("index.autoFight")}}</span>
            <SwitchButton :open="autoFight" @switchTrend="switchFight" />
          </div>
        </div>
        <div :style="{paddingRight:'.1rem',background:autoFight?'#112331':'#1C3447'}">
          <input type="number" v-model="fightTimes" v-if="autoFight">
          <input type="number" v-else>
          <span :style="{color:autoFight?'':'#3F5668'}">X</span>
        </div>
      </div>
      <div class="question">
          <IconButton :content="$t('index.ranking')" icon="ranking.png" @onClick="$router.push('/ranking')" />
          <IconButton :content="$t('index.question')" icon="question.png" @onClick="$router.push('/question')" />
      </div>
    </div>
    <!-- 游戏记录 -->
    <Forms />
    <BenefitProup v-if="benefitProup.show" :times="benefitProup.times" @closeBenefitProup="closeBenefitProup" />
  </div>
</template>

<script>
import Graph from "../../common/graph.js";
import Button from "../../components/Button.vue";
import IconButton from "../../components/IconButton.vue";
import SwitchButton from '../../components/SwitchButton.vue';
import Forms from "./forms.vue";
import Trend from './trend.vue';
import Benefit from '../../components/benefit.vue';
import BenefitProup from "../../components/benefitProup.vue";
import BalanceChange from "../../components/BalanceChange.vue";

import trendArr from '../../trend.js';
export default {
  components: {
    Button,
    IconButton,
    SwitchButton,
    Forms,
    Trend,
    Benefit,
    BenefitProup,
    BalanceChange
  },
  data() {
    return {
      amount: 0.0001,//余额
      pourAmount: 0.00001,//下注金额
      pour:0,
      fightTimes: 2.00,//自动逃跑倍数
      openTrend: false,//显示趋势图
      autoFight: true,//显示自动逃跑
      arr: trendArr,
      change:{
        show: false,
        type: 'add',//金额增加或减少
        amount: 0,//金额数量
      },
      benefitHint:{
        show: false,
        amount: 0
      },
      benefitProup:{
        show:false,
        times:50
      },
      trendState: 'next',
      flag: false,//玩家是否加入游戏
      watingNext: false,//玩家加入下一局游戏
    };
  },
  computed:{
    state(){
      return this.$store.getters.getState
    },
    times(){
      return this.$store.getters.getNowTimes
    },
    profit(){//当前收益
      let times = this.$store.getters.getNowTimes,amount = 0;
      
      if(times===0) return 0

      amount = this.fixValue(times,this.pourAmount,'*');
      /* if(amount < 0.000001){//将科学计数法转换为数字
        let fix = amount.toString().split("-")[1];
        amount = parseFloat(amount).toFixed(fix);
      }
      return amount */
      return amount.toFixed(7)
    }
  },
  watch:{
    state(){//游戏状态
      if(this.state===0){//开始
        this.graph.init();
        this.trendState = 'start';
        this.$store.commit('setGameState',1);
      }else if(this.state===1){//游戏中
        if(this.flag){//玩家已加入该场游戏
          this.trendState = 'fight';
        }else{
          this.trendState = 'next';
        }
      }else if(this.state===2){//结束（爆炸瞬间到下一局游戏准备）
        this.arr.push({issue:Number(this.arr[this.arr.length-1].issue)+1,times:this.$store.getters.getNowTimes});

        if(this.$refs.trend){
          this.$refs.trend.drawTrend();
        }else{
          this.$refs.historyTrend.scrollLeft = 10000;
        }

        if(this.watingNext){//玩家已下注下一局
          this.trendState = 'wating';
        }else{
          this.trendState = 'next';
        }
      }else if(this.state===3){//下一局游戏准备阶段
        if(this.watingNext){//上一局游戏期间下的注，余额扣除
          this.flag = true;
          this.watingNext = false;
          this.trendState = 'watingNotCancel';
          this.changeAmount('cut',this.pour);
          this.amount = this.fixValue(this.amount,this.pour,'-');
        }else{
          this.flag = false;
          this.trendState = 'start';
        }
      }
    },
    times(){//游戏倍数，自动逃跑
      if(this.flag&&this.autoFight&&this.fightTimes<=Number(this.times)){
        this.flag = false;
        this.fight(this.fightTimes)
      }
    }
  },
  updated(){
    if(this.$refs.historyTrend){
      this.$refs.historyTrend.scrollLeft = 10000;
    }
  },
  mounted() {
    this.createGraph();
    this.$refs.historyTrend.scrollLeft = 10000;
    this.graph.init();
  },
  methods: {
    fixValue(value1,value2,type){//精度缺失bug处理
      let length1 = 0,length2 = 0;
      if(value1.toString().split('.')[1]){
        length1 = value1.toString().split('.')[1].length
      }
      if(value2.toString().split('.')[1]){
        length2 = value2.toString().split('.')[1].length
      }
      let length = length1 > length2 ? Math.pow(10,length1) : Math.pow(10,length2);
      value1 = Math.round(value1*length);
      value2 = Math.round(value2*length);
      switch (type) {
        case '+':
          return (value1 + value2)/length
        case '-':
          return (value1 - value2)/length
        case '*':
          return (value1 * value2)/(length*length)
        case '/':
          return (value1 / value2)
        default:
          break;
      }
    },
    start(){//游戏准备阶段下注
      if(!this.pourAmount||this.pourAmount>this.amount){
        console.log('下注失败');
        return
      }
      this.flag = true;
      this.trendState = 'watingNotCancel';
      this.changeAmount('cut',this.pourAmount);
      this.amount = this.fixValue(this.amount,this.pourAmount,'-');
    },
    next(){//游戏已经开始，加入下一局游戏，在下一局游戏开始前都可以取消
      if(!this.pourAmount||this.pourAmount>this.amount){
        console.log('下注失败');
        return
      }
      this.pour = this.pourAmount;
      this.watingNext = true;
      this.trendState = 'wating';
    },
    wating(){//取消下注状态
      if(this.flag){
        this.trendState = 'start';
        this.flag = false;
      }
      if(this.watingNext){
        this.trendState = 'next';
        this.watingNext = false;
      }
    },
    fight(fightTimes){//游戏已经开始，且已加入游戏，可随时逃跑
      this.flag = false;
      //逃跑成功，并获得相应的奖励
      let times = this.$store.getters.getNowTimes,amount = this.fixValue(times,this.pourAmount,'*');

      if(fightTimes){//自动逃跑奖励
        amount = this.fixValue(fightTimes,this.pourAmount,'*')
      }
      
      //逃跑后金额增加，按钮提示为下一局
      this.changeAmount('add',amount);
      this.amount = this.fixValue(this.amount,amount,'+');
      this.trendState = 'next';
      //出现当局利益提示
      if(times >= 50){
        this.benefitProup.show = true;
      }else{
        this.benefitHint = {
          show: true,
          amount:amount
        }
        setTimeout(()=>{
          this.benefitHint.show = false
        },2000)
      }
    },
    changeAmount(type,amount){//修改余额数量
      this.change = {
        show:true,
        type,
        amount
      }
      setTimeout(()=>{
        this.change.show = false;
      },300)
    },
    changePour(type){//修改下注金额
      let min = 0.000001,max = 1;
      switch (type) {
        case '/2':
          if(this.pourAmount/2<min) {
            this.pourAmount = min;
            return
          }
          this.pourAmount = this.fixValue(this.pourAmount,2,'/');
          break;
        case '2':
          if(this.pourAmount*2>max) {
            this.pourAmount = max;
            return
          }
          this.pourAmount = this.fixValue(this.pourAmount,2,'*');
          break;
        case 'min':
          this.pourAmount = min;
          break;
        default:
          break;
      }
    },
    checkPourAmount(){//手动输入下注金额数量校验
      if(this.pourAmount < 0.000001 && this.pourAmount > 0){
        this.pourAmount = 0.000001;
      }else if(this.pourAmount > 1){
        this.pourAmount = 1;
      }
    },
    createGraph() {//创建游戏曲线图
      let canvas = this.$refs.canvas,
        cvs = this.$refs.cvs_scale;

      let ctx_scale = cvs.getContext("2d"),
        ctx = canvas.getContext("2d");
      this.graph = new Graph(ctx, ctx_scale);

      let userAgent = "pc";
      function browserRedirect() {
        if (/(iPhone|iPad|iPod|iOS)/i.test(window.navigator.userAgent)) {
          //iPhone 手机页面
          userAgent = "iphone";
        } else if (/(Android)/i.test(window.navigator.userAgent)) {
          //安卓手机页面
          userAgent = "android";
        } else {
          //电脑页面
          userAgent = "pc";
        }
      }
      browserRedirect();
      if (userAgent !== "pc") {
        let width = this.$refs.graphBox.clientWidth;

        canvas.width = width * 2;
        canvas.height = 200 * 2;
        cvs.width = width * 2;
        cvs.height = 200 * 2;
        this.graph.height = 200 * 2;
        this.graph.width = width * 2;
      } else {
        this.graph.height = 600 * 2;
        this.graph.width = 1000 * 2;
        this.graph.lenAxisX = 960 * 2;
        this.graph.lenAxisY = 500 * 2;
      }
      this.graph.initAxis()
    },
    switchTrend(){//切换趋势图
      this.openTrend = !this.openTrend;
      if(!this.openTrend){
        setTimeout(()=>{
          this.$refs.historyTrend.scrollLeft = 10000;
        })
      }
    },
    switchFight(){//切换自动逃跑
      this.autoFight = !this.autoFight;
    },
    closeBenefitProup(){
      this.benefitProup.show = false;
    },
    scrollAnimation(){//带滚动条，匀速动画
      console.log(this.$refs.historyTrend.scrollLeft);
      
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  padding: 0.02rem 0;
  overflow-y: auto;
}
.header {
  margin: 0.1rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
  >img{
    height: .29rem;
    width: .29rem;
  }
  .amount {
    height: 0.33rem;
    width: 1.75rem;
    border: solid 1px #283e4f;
    padding: 0 0.1rem;
    box-sizing: border-box;
    font-size: 0.13rem;
    display: flex;
    justify-content: space-between;
    align-items: center;
    >img{
      height: .21rem;
      width: .21rem;
      margin-right: .08rem;
    }
    span {
      color: #fff;
      flex: 1;
    }
  }
  .btns {
    margin-left: .45rem;
    display: flex;
    align-items: center;
    button {
      height: 0.33rem;
      width: 0.33rem;
      background: #283e4f;
      border-radius: 0.02rem;
      margin-left: 0.02rem;
    }
    button:nth-of-type(1) {
      background: #283e4f url("../../assets/img/wallet.png") 0.06rem 0.05rem
        no-repeat;
      background-size: 0.22rem 0.22rem;
    }
    button:nth-of-type(2) {
      background: #283e4f url("../../assets/img/message.png") 0.07rem 0.06rem
        no-repeat;
      background-size: 0.18rem 0.22rem;
    }
  }
}
.gameArea {
  background: #283e4f url('../../assets/img/bg.png') no-repeat 0 .121rem;
  background-size: contain;
  margin: 0.02rem 0.1rem 0.1rem;
  padding: 0.7rem 0.1rem 0.1rem;
  .gameTitle {
    display: flex;
    // justify-content: space-between;
    justify-content: flex-end;
    align-items: center;
    font-size: 0.13rem;
    margin: 0.1rem 0;
    span{
      vertical-align: middle;
      margin-right: .1rem;
    }
    >div{
      display: flex;
      align-items: center;
      img{
        height: .15rem;
        width: .15rem;
        margin-right: .08rem;
      }
    }
  }
  .trend {
    background: #1c2933;
    border-radius: 0.03rem;
    overflow: hidden;
    > div {
      background: #1c2933;
      font-size: 0.11rem;
      padding: 0.06rem;
      border-radius: 0.03rem;
      display: flex;
      dl {
        display: flex;
        align-items: center;
        line-height: 1.2;
        margin: 0 0.1rem;
        dd {
          height: 0.12rem;
          width: 0.12rem;
          border-radius: 50%;
          margin-right: 0.04rem;
        }
        dd.redbg {
          background: linear-gradient(to bottom, #ff092c 0%, #ff617b 100%);
        }
        dd.greenbg {
          background: linear-gradient(to bottom, #24ffaf 0%, #92ffe7 100%);
        }
        strong {
          color: #36ffd6;
        }
      }
    }
    .chart{
      background: #22333F;
      height: 1.57rem;
      margin: .03rem;
      padding: 0;
      position: relative;
    }
  }
  .graphCvas {
    height: 240px;
    width: 3.2rem;
    position: relative;
    canvas {
      position: absolute;
      top: -35%;
      left: 50%;
      transform: translate(-50%, 0) scale(0.5);
    }
  }
  .pour {
    font-size: 0.12rem;
    margin: .15rem 0;
    line-height: 2;
    .switch{
      display: flex;
      justify-content: flex-end;
      align-items: center;
      >span{
        margin-right: .05rem;
      }
    }
    >div{
      display: flex;
      justify-content: space-between;
      align-items: center;
      i{
        color: #39FFBE;
        margin-left: .08rem;
      }
      img{
        height: .21rem;
        width: .21rem;
        margin-right: .08rem;
        vertical-align: middle;
      }
    }
    > div:nth-last-of-type(1) {
      background: #112331;
      border-radius: 0.03rem;
      padding: 0.02rem;
      padding-left: .1rem;
      height: .38rem;
      box-sizing: border-box;
      color: #fff;
      margin-top: .04rem;
      >div{
        display: flex;
        align-items: center;
        button {
          height: 0.33rem;
          width: 0.33rem;
          background: #283e4f;
          border-radius: 0.02rem;
          margin-left: 0.04rem;
          font-size: .13rem;
          color: #7EA1BD;
        }
      }
    }
  }
  .question{
      display: flex;
      justify-content: space-between;
      margin: .2rem 0 .1rem;
  }
}
input{
  background: transparent;
  color: #fff;
  height: 100%;
  outline: none;
}
</style>